package org.psyduck.common.handler;

import org.psyduck.common.exception.BusinessException;
import org.psyduck.common.model.JsonBean;
import org.psyduck.common.model.JsonCode;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class BusinessExceptionHandler {

    /**
     * 参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object handleBindException(MethodArgumentNotValidException ex) {

        StringBuilder errMsgBuilder = new StringBuilder();

        ex.getBindingResult().getFieldErrors().forEach((fieldError) -> {
            errMsgBuilder.append(fieldError.getDefaultMessage());
        });

        return new JsonBean(JsonCode.BAD_REQUEST, errMsgBuilder.toString());
    }

    /**
     * 自定义异常
     */
    @ExceptionHandler(BusinessException.class)
    public JsonBean handleBusinessException(BusinessException e){
        return JsonBean.exception(e.getJsonCode(),e.getMessage());
    }

}